package io.huaguoguo.nio;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Map;

/**
 * 描述：  <br>
 * CreateDate: 2021/6/2 <br>
 *
 * @author huaguoguo
 */
@Slf4j
public class HttpDecoder {

    public HttpServletRequest decode(ByteBuffer buffer) {
        String httpMessage = new String(buffer.array());
        log.info("接受到的消息：\n" + httpMessage);
        String[] segments = httpMessage.split("\\n");

        // 转成map
        Map<String, String> reqMap = new HashMap<>();
        for (String segment : segments) {
            int index = segment.indexOf(":");
            if (index == -1) {
                continue;
            }
            String key = segment.substring(0, index);
            String value = segment.substring(index + 1, segment.length()).trim();
            reqMap.put(key, value);
        }
        MyRequest request = new MyRequest();
        // 请求行
        String[] reqRows = segments[0].split(" ");
        String method = reqRows[0];
        request.setMethod(method);
        request.setRequestURI(reqRows[1]);
        // host
        request.setRemoteHost(reqMap.get("Host"));
        return request;
    }
}
